const http = require('http')
const url = require('url')

const resposeData = {
    ID: 'ZhangSan',
    Name: '张三',
    RegisterData: '2021.8.1'
}
function toHTML(data) {
    return `
    <ul>
        <li><span>账号：</span><span>${data.ID}</span></li>
        <li><span>姓名：</span><span>${data.Name}</span></li>
        <li><span>注册时间：</span><span>${data.RegisterData}</span></li>
    </ul>
    `
}

const server = http.createServer((req, res) => {
    const {pathname} = url.parse(`http://${req.headers.host}${req.url}`)
    if (pathname === '/') {
        const accept = req.headers.accept // 前端期望的类型
        if (req.method === 'POST' || accept.indexOf('application/json') >= 0 ){
            res.writeHead(200, { 'Content-Type': 'application/json;' })
            res.end(JSON.stringify(resposeData))
        } else {
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
            res.end(toHTML(resposeData))
        }
        
        res.writeHead(200, { 'Content-Type': 'text/html;' })
        res.end('<h2>hello world</h2>')
    } else {
        res.writeHead(404, { 'Content-Type': 'text/html;' })
        res.end('<h2>404 not found</h2>')
    }
})

server.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
})